package cn.ll.service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.ll.po.Contract;
import cn.ll.po.ContractDAO;
import cn.ll.po.Department;

public class ContractService {
	ContractDAO contractDAO;

	/**
	 * 存储一个contract(协议)对象
	 * 
	 * @param contract
	 * @param department 
	 */
	public void save(Contract contract, Department department) {
		
		this.createContraceId(contract, department);
		
		contract.setStatus(0);

		contractDAO.save(contract);
	}

	private void createContraceId(Contract contract, Department department) {

		Date date = new Date();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

		String idHead = department.getDepShortName() + sdf.format(date);

		String idEnd = null;

		if (contract.getType() == "0") {
			idEnd = "N";
		} else {
			idEnd = "M";
		}

		String idPatten = idHead + "%" + idEnd;

		long count = contractDAO.countByIdPatten(idPatten);

		DecimalFormat df = new DecimalFormat("00000");
		String id = idHead + df.format(++count) + idEnd;

		contract.setId(id);
		if (contract.getType() == "0") {
			contract.setRootid(id);
		}
	}

	public void update(Contract contract) {
		// contractDAO.update(contract);
	}

	public Contract findById(String id) {
		Contract contract = contractDAO.findById(id);
		return contract;
	}

	/**
	 * 删除一个contract(协议)对象
	 * 
	 * @param contract
	 */
	public void delete(Contract contract) {
		contractDAO.delete(contract);
	}

	public void updateStatus(String contractid, int status) {
		Contract contract = contractDAO.findById(contractid);
		contract.setStatus(status);
		contractDAO.attachDirty(contract);
	}

	/**
	 * 
	 * @param p
	 * @param pn
	 * @return
	 */
	public List<Contract> selectContractList(int p, int pn) {
		List<Contract> lst = contractDAO.findAll();
		return lst;
	}

	/**
	 * 查看属于自己的协议
	 * 
	 * @param uid
	 * @param start
	 * @param limit
	 * @return
	 */
	public Map selectSelfContractList(String uid, int start, int limit) {
		Map map = contractDAO.selectSelfContractList(uid, start, limit);
		return map;
	}

	/**
	 * 查看所有协议
	 * 
	 * @param start
	 * @param limit
	 * @return
	 */
	public Map selectAllContractList(int start, int limit) {
		Map map = contractDAO.selectAllContractList(start, limit);
		return map;
	}

	public Map selectByContractStatus(int status, int start, int limit) {
		Map map = contractDAO.findByStatus(status, start, limit);
		return map;
	}

	public ContractDAO getContractDAO() {
		return contractDAO;
	}

	public void setContractDAO(ContractDAO contractDAO) {
		this.contractDAO = contractDAO;
	}
}
